<template>
  <div>
    <t-drawer v-model:visible="visible" :onClose="onClose" :on-overlay-click="onReset" :size="622" close-btn>
      <template #header>
        <div>{{ drawerTitle }}</div>
      </template>
      <div class="formBox">
        <t-form
            v-if="showForm"
            ref="form"
            :data="formData"
            :rules="RULE_RULES"
            @submit="onSubmit"

        >
          <div class="lineTitle">
            <span class="line"></span>
            <span class="title">基本信息</span>
          </div>

          <t-form-item label="规则名称" name="qualityRuleName" :label-align="'top'">
            <t-input v-model="formData.qualityRuleName" v-noSpace="formData.qualityRuleName" placeholder="请输入规则名称" :maxlength="25" show-limit-number></t-input>
          </t-form-item>

          <div class="lineTitle">
            <span class="line"></span>
            <span class="title">选择质检点</span>
            <span class="addBox">
              <t-button class="addBtn" theme="default" variant="text" @click="handleCardAdd">
              <template #icon>
                <svg-icon
                    :name="'icon-add'"
                    class-name="add-svg-icon"
                ></svg-icon>
              </template>
              新增质检点
            </t-button>
            </span>
          </div>

          <div class="cardContent">
            <div class="card"  v-for="(item, index) in formData.points" :key="index">
              <div class="cardTitle">
                <span class="cardName">质检点{{index + 1}}</span>
                <span class="cardDel" v-show="formData.points.length > 1">
                  <t-button class="" theme="default" variant="text" @click="handleCardDel(item, index)">
                    <template #icon>
                      <svg-icon
                          :name="'icon-itemDel'"
                          class-name="itemDel-svg-icon"
                      ></svg-icon>
                    </template>
                    删除
                  </t-button>
                </span>
              </div>
              <div class="cardBody">

                <t-form-item label="匹配侧" requiredMark name="match" :label-align="'top'"  class="c_aside">
                  <t-radio-group v-model="item.match" @change="matchChange(item)">
                    <t-radio :value="0">座席</t-radio>
                    <t-radio :value="1">客户侧</t-radio>
                    <t-radio :value="2">触发条件</t-radio>
                  </t-radio-group>
                </t-form-item>

<!--                座席 ｜ 客户侧显示-->
                <template v-if="item.match !== 2">
                  <t-form-item
                      label="质检点类型"
                      name="type"
                      :label-align="'top'"
                      requiredMark
                  >
                    <t-select v-model="item.type" @change="pointTypeChange(item)">
                      <t-option :key="0" label="词类"  :value="0" />
                      <t-option :key="1" label="正则表达式" :value="1" />
                      <t-option :key="2" label="插话/抢话" :value="2" />
                      <t-option :key="3" label="语速" :value="3" />
                      <t-option :key="4" label="冷场" :value="4" />
                    </t-select>
                  </t-form-item>

                  <t-form-item
                      :label="pointLabel(item.type)"
                      name="typeId"
                      requiredMark
                      :label-align="'top'">
                    <t-select v-model="item.typeId">
                      <t-option v-for="opt in item.options" :key="opt.id" :label="opt.name" :value="opt.id" />
                    </t-select>
                  </t-form-item>
                </template>

<!--                触发条件显示-->
                <template v-else>
                  <t-form-item label="触发条件" :label-align="'top'" name="" requiredMark id="triggerSty">
                    <t-space style="gap: 8px; margin-top: 12px">
                      <div class="first_c">
                        <t-select v-model="item.triggerCondition.typeFirst" @change="triggerFirstChange(item.triggerCondition)" style="width: 166px !important" placeholder="选择触发条件">
                          <t-option :key="0" label="座席" :value="0" />
                          <t-option :key="1" label="客户侧" :value="1" />
                        </t-select>
                      </div>
                      <div class="first_c">
                        <span class="v_text">,触发</span>
                        <t-select v-model="item.triggerCondition.pointTypeFirst" @change="triggerFirstChange(item.triggerCondition)" placeholder="质检类型">
                          <t-option :key="0" label="词类"  :value="0" />
                          <t-option :key="1" label="正则表达式" :value="1" />
                          <t-option :key="2" label="插话/抢话" :value="2" />
                          <t-option :key="3" label="语速" :value="3" />
                          <t-option :key="4" label="冷场" :value="4" />
                        </t-select>
                      </div>
                      <div class="first_c">
                        <t-select v-model="item.triggerCondition.pointIdFirst" placeholder="质检点">
                          <t-option v-for="opt in item.triggerCondition.optionsFirst" :key="opt.id" :label="opt.name" :value="opt.id" />
                        </t-select>
                      </div>
                    </t-space>

                    <t-space style=" gap: 8px;justify-content: center;align-items: center">
                      <div class="first_c">
                        <t-input-number class="countInput" theme="normal" v-model="item.triggerCondition.count" placeholder="请输入数字"></t-input-number>
                      </div>
                      <div>
                        <t-select class="m_select" v-model="item.triggerCondition.type" placeholder="选择触发条件">
                          <t-option :key="0" label="句" :value="0" />
                          <t-option :key="1" label="秒" :value="1" />
                        </t-select>
                      </div>
                      <div class="m_text">内</div>
                    </t-space>

                    <t-space style="gap: 8px; margin-top: 12px">
                      <div class="first_c">
                        <t-select v-model="item.triggerCondition.typeSecond" @change="triggerSecondChange(item.triggerCondition)" style="width: 166px !important" placeholder="选择触发条件">
                          <t-option :key="0" label="座席"  :value="0" />
                          <t-option :key="1" label="客户侧" :value="1" />
                        </t-select>
                      </div>
                      <div class="first_c">
                        <span class="v_text">,触发</span>
                        <t-select v-model="item.triggerCondition.pointTypeSecond" @change="triggerSecondChange(item.triggerCondition)" placeholder="质检类型">
                          <t-option :key="0" label="词类"  :value="0" />
                          <t-option :key="1" label="正则表达式" :value="1" />
                          <t-option :key="2" label="插话/抢话" :value="2" />
                          <t-option :key="3" label="语速" :value="3" />
                          <t-option :key="4" label="冷场" :value="4" />
                        </t-select>
                      </div>
                      <div class="first_c">
                        <t-select v-model="item.triggerCondition.pointIdSecond" placeholder="质检点">
                          <t-option v-for="opt in item.triggerCondition.optionsSecond" :key="opt.id" :label="opt.name" :value="opt.id" />
                        </t-select>
                      </div>
                    </t-space>
                  </t-form-item>
                </template>

                <t-form-item label="匹配标签" :label-align="'top'" name="tagId">
                  <t-cascader
                      v-model="item.tagId"
                      :options="tagOptions"
                      :show-all-levels="false"
                      :min-collapsed-num="3"
                      :keys="{
                        label: 'tagName',
                        value: 'id'
                      }"
                      multiple>
                  </t-cascader>
                </t-form-item>

<!--                规则关系-->
                <t-form-item name="logicalType" class="rule-type" v-if="index !== 0">
                  <t-space style="gap: 11px; width: 100%">
                    <div class="line-type">
                      <div></div>
                    </div>
                    <div>
                      <t-select v-model="item.logicalType">
                        <t-option key="1" label="和" :value="1" />
                        <t-option key="0" label="或" :value="0" />
                      </t-select>
                    </div>
                    <div class="line-type">
                      <div></div>
                    </div>
                  </t-space>
                </t-form-item>

              </div>
            </div>
          </div>

          <div class="lineTitle">
            <span class="line"></span>
            <span class="title">评分配置</span>
          </div>
          <t-form-item id="boxFatal1" v-if="formData.fatal === 0" label="触发类型" name="triggerType" :label-align="'left'" requiredMark :label-width="67">
            <t-space class="spaceItem" style="gap: 8px;">
              <t-radio-group v-model="formData.triggerType">
                <t-radio :value="0">常规</t-radio>
                <t-radio :value="1">计数</t-radio>
              </t-radio-group>
            </t-space>
          </t-form-item>
          <t-form-item
              class="shortInput"
              v-if="formData.fatal === 0 && formData.triggerType === 1"
              label="触发次数"
              name="triggerCount"
              :label-align="'left'"
              :label-width="67"
              requiredMark
          >
            <t-input-number
                theme="normal"
                v-model="formData.triggerCount"
                class="input1"
                :min="2"
                placeholder="请输入触发次数">
            </t-input-number>
          </t-form-item>

          <t-form-item class="shortInput" v-if="formData.fatal === 0" label="初始分" name="initialScore" :label-align="'left'" :label-width="53">
            <t-input-number theme="normal" v-model="formData.initialScore" placeholder="请输入初始分值"></t-input-number>
          </t-form-item>
          <t-form-item id="shortInput" v-if="formData.fatal === 0" label="质检分" name="score" :label-align="'left'" :label-width="53">
            <t-space class="spaceItem" style="gap: 8px;">
              <t-select v-model="formData.scoreType">
                <t-option key="1" label="加分" :value="1" />
                <t-option key="0" label="扣分" :value="0" />
              </t-select>
              <t-input-number theme="normal" v-model="formData.score" class="input1" placeholder="请输入分值"></t-input-number>
              <div class="s_multiple">
                <template v-if="formData.scoreType !== null">
                  <span class="is_dc">多次{{ ['扣分', '加分'][formData.scoreType] }}</span>
                  <t-checkbox @change="handleMultiple" :checked="formData.multiple === 1">
                  </t-checkbox>
                </template>
              </div>
            </t-space>
          </t-form-item>

          <t-form-item class="helpFormItem" v-if="formData.multiple">
            <span class="helpText">
              <span class="desc">
                  <svg-icon
                      :name="'icon-warn'"
                      class-name="warn-svg-icon"
                  ></svg-icon>
                  请确认【初始分】与【质检分】符合多次扣分/加分标准
                </span>
            </span>
          </t-form-item>

          <t-form-item id="boxFatal" label="是否致命" name="fatal" :label-align="'left'" :label-width="67">
            <t-space class="spaceItem" style="gap: 8px;">
                <t-radio-group v-model="formData.fatal" @change="handleFatal">
                  <t-radio :value="1">是</t-radio>
                  <t-radio :value="0">否</t-radio>
                </t-radio-group>
                <span class="desc" v-show="formData.fatal === 1">
                  <svg-icon
                      :name="'icon-warn'"
                      class-name="warn-svg-icon"
                  ></svg-icon>
                  当触发质检点后，此模板分数直接清零
                </span>
            </t-space>
          </t-form-item>

          <t-form-item class="submitBox">
            <t-space size="small">
              <t-button theme="default" variant="base" @click="onReset">取消</t-button>
              <t-button class="hoverBlue" theme="primary" type="submit">保存</t-button>
            </t-space>
          </t-form-item>

        </t-form>
      </div>
<!--      自定义 footer 不可删除-->
      <template #footer>
      </template>
    </t-drawer>
  </div>
</template>

<script setup>
import {getCurrentInstance, reactive, ref, watch, computed, nextTick} from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import {
  checkRuleName,
  detailQualityRule,
  editQualityRule,
  newQualityRule,
  pointListByType,
  tagList,
  checkScore
} from "../../../../api/qualitySet/qualityTemplate";
import cache from '@/utils/cache.js'
const pageInstance = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
  drawerVisible: Boolean,
  onResetDrawerVisible: Function,
  drawerTitle: String,
  templateId: String, // 模版id
  inspectionItemId: String, // 质检项id
  qualityRuleId: String, // row id
  templateScore: Number, // 当前质检规则总分
})

const templateType = ref() // 模版类型
templateType.value = JSON.parse(cache.getSession('templateInfo'))['type']

const getOptions = (item) => { // 编辑时遍历调用 用来回显
  if(item.match !== 2) {
    let data = {
      type: item.type,
      matchingSide: item.match
    }
    pointListByType(data).then(res => {
      item.options = res.data
    }).catch(error => {
      console.log(error)
    })
  } else {

   nextTick(() => {
     let data = item.triggerCondition
     pointListByType({
       type: data.typeFirst,
       matchingSide: data.pointTypeFirst,
     }).then(res => {
       data.optionsFirst = res.data
     })

     pointListByType({
       type: data.typeSecond,
       matchingSide: data.pointTypeSecond
     }).then(res => {
       data.optionsSecond = res.data
     })
   })
  }
}

const showForm = ref(false) // 用来解决编辑回显 数据未组装好 就渲染了
const beforeInitialScore = ref(0) // 保存编辑初始分值之前的数据 用来判断输入是否符合规则
const getDetailData = () => {
  if(props.qualityRuleId !== '') { // 编辑
    Object.assign(formData, {})
    let data = {
      templateId: props.templateId,
      qualityRuleId: props.qualityRuleId
    }
    detailQualityRule(data).then(res => {
      let obj = { ...res.data }

      beforeInitialScore.value = JSON.parse(JSON.stringify(obj.initialScore))
      let mapPoints =  obj.points.map(item => {
        return  {
          type: item.type,
          match: item.match,
          typeId: item.id,
          tagId: item.tagId,
          logicalType: item.logicalType,
          triggerCondition: {
            typeFirst: item.triggerCondition.typeFirst,
            typeSecond: item.triggerCondition.typeSecond,
            pointTypeFirst: item.triggerCondition.pointTypeFirst,
            pointTypeSecond: item.triggerCondition.pointTypeSecond,
            pointIdFirst: item.triggerCondition.pointIdFirst,
            pointIdSecond: item.triggerCondition.pointIdSecond,
            count: item.triggerCondition.count,
            type: item.triggerCondition.type
          }
        }
      })
      obj.points = mapPoints
      obj.level = res.data.level
      Object.assign(formData, obj)
      nextTick(() => {
        formData.points.forEach(item => {
          getOptions(item)
        })
      })
      console.log(formData)
      showForm.value = true
    })
  } else {
    showForm.value = true
    beforeInitialScore.value = 0
    formData.triggerCount = null
  }
}

const visible = ref(false);
const tagOptions = ref([])
watch(() => props.drawerVisible, (newVal, oldVal) => {
  if(newVal.toString() === 'true') {
    visible.value = props.drawerVisible

    // 处理 获取匹配标签数据
    tagList(JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']).then(res => {
      let ary = [
        {
          type: 0,
          tagName: '座席侧',
          disabled: false,
          children: []
        },
        {
          type: 1,
          tagName: '客户侧',
          disabled: false,
          children: []
        }
      ]
      res.data.forEach(item => {
        if(item.type === 0) {
          ary[0].children.push(item)
        } else {
          ary[1].children.push(item)
        }
      })
      ary.forEach(item => {
        if(item.children.length === 0) {
          item.disabled = true
        }
      })
      tagOptions.value = ary
    })
    // 获取详情数据
    showForm.value = false
    getDetailData()
  } else {
    visible.value = props.drawerVisible
    formData.fatal = 0
    formData.triggerType = 0
  }
})
const onClose = () => {
  resetForm()
  pageInstance.refs.form.reset()
  emit('resetDrawerVisible', false)
}
const onReset = () => {
  resetForm()
  pageInstance.refs.form.reset()
  emit('resetDrawerVisible', false)
}
const resetForm = () => {
  formData.points = [
    {
      type: null,
      match: 0,
      typeId: '', // 用来临时存储质检点id 后续根据id组装 后端所需数据
      options: [],
      tagId: [],
      logicalType: 1, // 规则关系 默认和
      triggerCondition: { // 触发条件
        typeFirst: null,
        typeSecond: null,
        pointTypeFirst: null,
        pointTypeSecond: null,
        pointIdFirst: null,
        pointIdSecond: null,
        count: null,
        optionsFirst: null,
        optionsSecond: null,
        type: null
      }
    }
  ]
  formData.points.options = []
  formData.score = null
  formData.multiple = 0
  showForm.value = false
  formData.scoreType = 0
  formData.fatal = 0
  formData.triggerType = 0
}

// form
// 规则名称查重
const ruleNameValidator = (val) =>
    new Promise((resolve) => {
      if(val === '' || val === undefined) {
        resolve({ result: false, message: '请输入规则名称', type: 'error' })
      } else {
        let data = {
          templateId: props.templateId,
          inspectionId: props.inspectionItemId,
          qualityRuleName: val
        }
        let type = props.qualityRuleId !== '' ? 1: 0
        checkRuleName(data, type).then(res => {
          if(res.data) {
            resolve(true)
          } else {
            resolve({ result: false, message: '规则名称重复', type: 'error' })
          }
        })
      }
    });

const initialScoreValidator = (val) =>
    new Promise((resolve) => {
      // console.log('模版类型', templateType.value)
      if(val === '' || val === undefined) {
        resolve({ result: false, message: '请输入初始分值', type: 'error' })
      } else if(val < 0) {
        resolve({ result: false, message: '初始分值最小为0分', type: 'error' })
      } else if(val > 100 && templateType.value === 0) { // 智能模版 限制初始分不可大于100
        resolve({ result: false, message: '初始分值最大为100分', type: 'error' })
      } else {
        // 判断新增或修改后分值是否超过 100
        // 原分：新增的话是0 // 编辑的话就是修改前的分值
        let checkedScore = props.qualityRuleId !== '' ? beforeInitialScore.value : 0
        let total = props.templateScore // 总分：
        let value = total + val - checkedScore

        if(value > 100 && templateType.value === 0) { // 智能模版 限制总分不可大于100
          resolve({ result: false, message: '您设置的模板总分已超过100分！', type: 'error' })
        } else {
          formData.score = JSON.parse(JSON.stringify(val))
          resolve(true)
        }
      }
    })

const scoreValidator = (val) =>
    new Promise((resolve) => {
      if(val === '' || val === undefined) {
        resolve({result: false, message: '请输入分值', type: 'error'})
      } else if(formData.initialScore && formData.initialScore < val) {
        resolve({result: false, message: '不可大于初始分值', type: 'error'})
      } else {
        resolve(true)
      }
    })
const countValidator = (val) =>
    new Promise(resolve => {
      if(formData.triggerType === 0) { // 触发类型常规不需要校验
        resolve(true)
      } else {
        if(val === '' || val === undefined) {
          resolve({result: false, message: '请输入触发次数', type: 'error'})
        } else if(val < 2) {
          resolve({result: false, message: '触发次数最小值为2', type: 'error'})
        } else {
          resolve(true)
        }
      }
    })

const RULE_RULES = {
  qualityRuleName: [
      { required: true, validator: ruleNameValidator, trigger: 'blur' }
  ],
  initialScore: [
      { required: true, message: '请输入初始分值' },
      { validator: initialScoreValidator, trigger: 'blur', }
  ],
  multiple: [{ required: true, message: '请选择是或否' }],
  fatal: [{ required: true, message: '请选择是否致命' }],
  triggerType: [{ required: true, message: '请选择触发类型' }],
  triggerCount: [
      // { required: true, message: '请输入触发次数' },
      { validator: countValidator, trigger: 'blur', }
  ],
  scoreType: [{ required: true, message: '请选择是或否' }],
  score: [
      { required: true, message: '请输入分值' },
      { validator: scoreValidator, trigger: 'blur', }
  ],
}
const formData = reactive({
  templateId: props.templateId,
  inspectionId: '',
  match: 0, // 这个是写死的
  qualityRuleName: '',
  points: [
    {
      type: null,
      match: 0,
      typeId: '', // 用来临时存储质检点id 后续根据id组装 后端所需数据
      options: [],
      tagId: [],
      logicalType: 1, // 规则关系默认和
      triggerCondition: { // 触发条件
        typeFirst: null,
        typeSecond: null,
        pointTypeFirst: null,
        pointTypeSecond: null,
        pointIdFirst: null,
        pointIdSecond: null,
        count: null,
        optionsFirst: null,
        optionsSecond: null,
        type: null
      }
    }
  ],
  initialScore: null,
  scoreType: 0,
  score: null, // 分值
  multiple: 0, // 是否多次扣分
  fatal: 0, // 是否致命
  triggerType: 0, // 触发类型
  triggerCount: null, // 触发次数
})

// 动态label
const pointLabel = (type) => {
  if(type === null || type === undefined) {
    return '选择质检点'
  } else {
    return `选择${['词类', '正则表达式', '插话/抢话', '语速', '冷场'][type]}质检点`
  }
}
// 质检点类型改变
const pointTypeChange = (item) => {
  item.typeId = ''
  // 请求质检点列表
  let data = {
    type: item.type,
    matchingSide: item.match
  }
  // console.log('item121212', item)
  pointListByType(data).then(res => {
    item.options = res.data
  })
}
// 触发条件的质检点列表
const triggerFirstChange = (item) => {
  item.pointIdFirst = null
  if(item.pointTypeFirst !== null && item.typeFirst !== null) {
    let data = {
      type: item.typeFirst,
      matchingSide: item.pointTypeFirst,
    }
    pointListByType(data).then(res => {
      item.optionsFirst = res.data
    })
  }
}
const triggerSecondChange = (item) => {
  item.pointIdSecond = null
  if(item.pointTypeSecond !==null && item.typeSecond !== null) {
    let data = {
      type: item.typeSecond,
      matchingSide: item.pointIdSecond,
    }
    pointListByType(data).then(res => {
      item.optionsSecond = res.data
    })
  }
}
// 座席侧改变
const matchChange = (item) => {
  if(item.match !== 2) {
    // 清空触发条件的数据
    item.triggerCondition.typeFirst = null
    item.triggerCondition.typeSecond = null
    item.triggerCondition.pointTypeFirst = null
    item.triggerCondition.pointTypeSecond = null
    item.triggerCondition.pointIdFirst = null
    item.triggerCondition.pointIdSecond = null
    item.triggerCondition.type = null
    item.triggerCondition.count = null


    if(item.type === null || item.type === undefined) return
    item.typeId = ''
    if(item.type === 0) { // 只有词类分座席或者客户侧 请求下拉数据
      let data = {
        type: item.type,
        matchingSide: item.match
      }
      pointListByType(data).then(res => {
        item.options = res.data
      })
    }
  } else {
    // 清空座席用户侧数据的数据
    item.type = null
    item.typeId = []
  }
}

const handleCardAdd = () => { // 新增质检点
  let obj = {
    type: null,
    match: 0,
    typeId: '',
    options: [],
    tagId: [],
    logicalType: 1,
    triggerCondition: { // 触发条件
      typeFirst: null,
      typeSecond: null,
      pointTypeFirst: null,
      pointTypeSecond: null,
      pointIdFirst: null,
      pointIdSecond: null,
      count: null,
      optionsFirst: null,
      optionsSecond: null,
      type: null
    }
  }
  formData['points'].push(obj)
}
const handleCardDel = (item, i) => {
  formData.points = formData.points.filter((item, index) => {
    return index !== i
  })
}

// 是否多次
const handleMultiple = () => {
  formData.multiple = formData.multiple === 1 ? 0 : 1
}

const checkPoints = (ary) => {
  if (ary.length === 0) {
    return true
  }
  if(ary[0].type === null || ary[0].type === undefined) {
    MessagePlugin.error('请选择质检点类型')
    return false
  } else if (ary[0].typeId === '') {
    MessagePlugin.error('请选择质检点')
    return false
  }
}

const handleFatal = (value) => {
  if(value === 1) {
    formData.initialScore = 0
    formData.scoreType = 0
    formData.score = 0
    formData.multiple = 0
  } else {
    formData.initialScore = null
    formData.scoreType = 0
    formData.score = null
    formData.multiple = 0
  }
}

// 检测质检点
const checkPointsPro = (ary) => {
  return new Promise((resolve, reject) => {
    ary.forEach((item, index) => {
      if(item.match !== 2) {  // 检测座席或客户侧
        if(item.type === null || item.type === undefined || item.typeId === '') {
          resolve({flag: false, index: index + 1})
        }
      } else { // 检测触发条件
        if (item.triggerCondition.typeFirst === null ||
            item.triggerCondition.typeSecond === null ||
            item.triggerCondition.pointTypeFirst === null ||
            item.triggerCondition.pointTypeSecond === null ||
            item.triggerCondition.pointIdFirst === null ||
            item.triggerCondition.pointIdSecond === null ||
            item.triggerCondition.type === null ||
            item.triggerCondition.count === null)
        {
          resolve({flag: false, index: index + 1})
        }
      }
    })
    resolve({ flag: true })
  })
}
const onSubmit = async ({ validateResult, firstError }) => {
  formData.inspectionId = props.inspectionItemId
  if (validateResult === true) {
    // 分值是否输入了
    if(formData.fatal === 0 && (formData.score === null || formData.score === undefined)) {
      MessagePlugin.error('请输入分值！')
      return
    }

    let res = await checkPointsPro(formData.points)

    if(res.flag) {
      // console.log('flag points', formData)
      // 组装符合后端数据
      formData.points.forEach(item => {
        if(item.options) {
          item.options = item.options.forEach(e => { // 将选中 options 的数据放到item中
            if(item.typeId === e.id) {
              for (let key in e) {
                if(!item[key]) {
                  item[key] = e[key]
                }
              }
            }
          })
        }
      })
      // 判断当前触发类型(常规触发次数默认传一)
      formData.triggerCount = formData.triggerType === 0 ? 1 : formData.triggerCount

      // 判断当前是新增还是编辑
      if(props.qualityRuleId === '') { // 新增
        if(formData.qualityRuleId) delete formData.qualityRuleId
        formData.level = 0 // 新增默认 为0 非父飞子
        newQualityRule(formData).then(res => {
          // console.log('newQualityRule', res)
          if(res.code === 0) {
            resetForm()
            pageInstance.refs.form.reset()
            emit('resetDrawerVisible', true)
            MessagePlugin.success('新增成功！')
          } else {
            // 如果规则名称重复 则需要将组装好的数据还原
          }
        })
      } else { // 编辑
        formData.qualityRuleId = props.qualityRuleId
        editQualityRule(formData).then(res => {
          if(res.code === 0) {
            resetForm()
            pageInstance.refs.form.reset()
            emit('resetDrawerVisible', true)
            MessagePlugin.success('编辑成功！')
          }
        })
      }
    } else {
      let str = `请确认质检点${res.index}是否配置完毕！`
      await MessagePlugin.error(str)
    }
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
  }
}
</script>

<style lang="scss" scoped>
:deep(.t-drawer__body) {
  padding: 23px 0;
}
:deep(.t-drawer__footer) {
  height: 60px;
  margin: 0;
  padding-top: 19px;
  .t-button {
    display: none;
  }
}
.formBox {
  :deep(.t-form) {
    #boxFatal {
      .desc {
        width: 272px;
        height: 28px;
        opacity: 1;
        border-radius: 7px;
        background: rgba(242, 242, 242, 1);
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 3px 10px 3px 10px;

        font-size: 12px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.9);
        .warn-svg-icon {
          height: 16px;
          width: 16px;
          margin-right: 8px;
        }
      }
      .t-radio {
        margin-right: 11px;
      }
      .t-radio__label {
        font-size: 12px;
        font-weight: 400;
        color: rgba(92, 91, 91, 1);
      }
    }
    #boxFatal1 {
      //.t-input__extra {
      //  position: absolute;
      //  left: 192px;
      //}
      .spaceItem {
        display: flex;
        align-items: center;
      }
      .t-radio {
        margin-right: 11px;
      }
      .t-radio__label {
        font-size: 12px;
        font-weight: 400;
        color: rgba(92, 91, 91, 1);
      }
      .tg_count {
        position: relative;
        span {
          font-size: 12px;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.9);
          display: inline-block;
          margin: 0 11px 0 8px;
        }
        .t-input__wrap {
          width: 110px !important;
        }
        .t-input {
          height: 28px;
          width: 110px !important;
        }

      }
    }
    .helpFormItem {
      margin-top: -14px;
      margin-bottom: 20px !important;
      .t-form__label {
        display: none;
      }
      .t-form__controls {
        margin-left: 0 !important;
      }
      .helpText {
        //position: absolute;
        left: 0;
        top: 30px;
        color: rgba(0, 0, 0, 0.4);
        font-size: 12px;
        .desc {
          width: 363px;
          height: 28px;
          opacity: 1;
          border-radius: 7px;
          background: rgba(242, 242, 242, 1);
          display: flex;
          justify-content: flex-start;
          align-items: center;
          padding: 3px 10px 3px 10px;

          font-size: 12px;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.9);
          .warn-svg-icon {
            height: 16px;
            width: 16px;
            margin-right: 8px;
          }
        }
      }
    }
    #shortInput {
      position: relative;
      .t-input__extra {
        position: absolute;
        top: 33px;
        left: 118px;
      }
      .input1 {
        width: 110px;
      }
      .spaceItem {
        display: flex;
        align-items: center;
        .t-select__wrap {
          width: 110px !important;
        }
        .t-input__wrap {
          width: 110px !important;
        }
        .t-input {
          height: 28px;
          width: 110px !important;
        }
        .s_multiple {
          //background-color: red;
          display: flex;
          justify-content: center;
          align-items: flex-start;
          .is_dc {
            font-size: 12px;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.9);
            display: inline-block;
            margin: 0 11px 0 0;
          }
          .t-checkbox {
            margin-top: 2px;
            width: 16px;
            height: 16px;
            opacity: 1;
            border-radius: 2px;
          }
          .t-checkbox__label {
            margin-left: 0;
          }

          .t-is-checked {
            background: rgba(30, 117, 254, 1) !important;
          }
        }

        .t-radio {
          margin-right: 11px;
        }
        .t-radio__label {
          font-size: 12px;
          font-weight: 400;
          color: rgba(92, 91, 91, 1);
        }
      }
    }
    .shortInput {
      .t-input {
        height: 28px;
        width: 110px !important;
      }
    }
    .t-form__item {
      padding-left: 16px;
      margin-bottom: 22px;
      .t-form__label {
        font-size: 12px;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.9);
        text-align: left;
        vertical-align: top;
      }
      .t-form__controls {
        height: 28px;
        .t-select__wrap {
          width: 342px !important;
        }
        .t-input {
          height: 28px;
          width: 342px;
        }
        .t-cascader {
          height: 28px;
          .t-input__wrap {
            height: 28px;
            .t-input {
              height: 28px;
              min-height: 28px;
              .t-tag {
                //background-color: red;
                height: 18px;
                border-radius: 4px;
                font-size: 10px;
                font-weight: 400;
                line-height: 18px;
                color: rgba(84, 82, 82, 1);
              }
            }
          }
        }
      }
    }
    .type_class {
      .t-form__label {
        padding-right: 4px !important;
      }
    }

    .submitBox {
      position: fixed;
      bottom: -10px;
      right: 20px;
      .t-button--theme-default {
        background-color: white;
        border: none;
        width: 60px;
        height: 28px;
      }
      .t-button--theme-primary {
        width: 60px;
        height: 28px;
        opacity: 1;
        border-radius: 3px;
        background: rgba(30, 117, 254, 1);
      }
    }
  }
  .lineTitleLabel {
    padding-bottom: 8px !important;
  }
  .lineTitle {
    display: flex;
    align-items: center;
    padding-bottom: 16px;
    padding-right: 20px;
    .line {
      display: inline-block;
      height: 21px;
      width: 3px;
      border-right: 3px;
      background: rgba(30, 117, 254, 1);
    }
    .title {
      display: inline-block;
      font-size: 13px;
      font-weight: 600;
      color: rgba(43, 43, 43, 1);
      margin-left: 16px;
    }
    .addBox {
      margin-left: auto;
      .addBtn {
        font-size: 11px;
        font-weight: 400;
        color: rgba(30, 117, 254, 1);
        margin: 0;
        padding: 0;
      }
      .add-svg-icon {
        height: 16px;
        width: 16px;
        margin-right: 2px;
      }
    }
  }
  .cardContent {
    margin: 0 22px 0 16px;
    .card {
      border: 1px solid rgba(238, 238, 238, 1);
      border-radius: 2px;
      margin-bottom: 52px;
      .cardTitle {
        padding: 0 12px 0 16px;
        height: 35px;
        opacity: 1;
        background: rgba(247, 247, 247, 1);
        display: flex;
        align-items: center;
        .cardName {
          font-size: 11px;
          font-weight: 600;
          color: rgba(43, 43, 43, 1);
        }
        .cardDel {
          margin-left: auto;
          .itemDel-svg-icon {
            height: 16px;
            width: 16px;
          }
          :deep(.t-button) {
            margin: 0;
            padding: 0;
            font-size: 10px;
            font-weight: 400;
            color: rgba(245, 115, 126, 1);
          }
        }
      }
      .cardBody {
        //.c_aside {
        //  .t-radio-group {
        //    .t-radio {
        //      background-color: red;
        //      display: flex;
        //      justify-content: center;
        //      align-items: center;
        //      .t-radio__label {
        //        line-height: 28px !important;
        //      }
        //    }
        //  }
        //}
        position: relative;
        padding-top: 8px;
        padding-bottom: 7px;
        :deep(.t-radio-group) {
          .t-radio__label {
            font-size: 12px;
            font-weight: 400;
            color: rgba(92, 91, 91, 1);
            height: 28px !important;
            line-height: 28px !important;
          }
        }
        :deep(.t-form__item) {
          margin-bottom: 10px;
          .t-form__label {
            height: 28px !important;
          }
          .t-form__label--top {
            min-height: 28px !important;
          }
          .t-select__wrap {
            width: 323px !important;
          }
          .t-input {
            width: 323px !important;
          }
        }
        .rule-type {
          margin-left: 0 !important;
          padding-left: 0 !important;
          width: 574px;
          :deep(.t-form__label) {
            display: none;
          }
          :deep(.t-form__controls) {
            margin-left: 0 !important;
          }
          position: absolute;
          top: -77px;
          :deep(.t-space-item) {
            width: calc((100% - 68px) / 2);
            .line-type {
              display: flex;
              justify-content: center;
              align-items: center;
              height: 100%;
              div {
                width: 100%;
                height: 0;
                opacity: 1;
                background: rgba(204, 204, 204, 1);
                border: 0.8px solid rgba(229, 229, 229, 1);
              }
            }
          }
          :deep(.t-space-item:nth-child(2)) {
            width: 46px;
            .t-select__wrap {
              width: 46px !important;
              border: none;
              .t-select {
                border: none;
              }
              .t-input {
                border: none !important;
                width: 46px !important;
                padding-right: 1px;
                .t-input__suffix-icon {
                  width: 16px;
                }
              }
              .t-is-focused {
                box-shadow: none;
              }
            }
          }
        }
      }
    }
    .card:last-child {
      margin-bottom:23px;
    }
  }

}
:deep(.t-popup) {
  .t-checkbox__input {
    display: none !important;
  }
}

</style>
<style lang="scss">
//  不加scope 需要确保是唯一标签
#triggerSty {
  height: 144px;
  .t-form__controls-content {
    display: block;
  }
  .first_c {
    display: flex;
    justify-content: center;
    align-items: center;
    .v_text {
      font-size: 12px;
      font-weight: 400;
      color: rgba(12, 13, 14, 1);
      margin-right: 8px;
    }
    .countInput {
      width: 166px;
      .t-input {
        margin-top: 12px;
        width: 166px !important;
      }
    }
    .t-select__wrap {
      width: 166px !important;
      .t-select-input{
        .t-input {
          width: 166px !important;
        }
      }
    }
  }
  .m_select {
    margin-top: 12px;
    width: 202px !important;
    .t-select-input {
      width: 202px;
      .t-input {
        width: 202px !important;
      }
    }
  }
  .m_text {
    margin-top: 12px;
    text-align: left;
    font-size: 12px;
    font-weight: 400;
    line-height: 22px;
    color: rgba(12, 13, 14, 1);
  }
  .t-input .t-input__inner::placeholder {
    font-size: 12px;
    font-weight: 400;
    color: rgba(12, 13, 14, 1);
  }
}
</style>
